/* 
 * ProductExportWizard.java
 * Copyright (c) 2008 WayfarerX.net and others (see below).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * Contributors:
 *   WayfarerX (2008) - Initial documentation & implementation.
 * 
 */
package net.wayfarerx.tools.export.internal;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.pde.internal.ui.wizards.exports.ProductExportWizardPage;

/**
 * Extension of the base PDE product export wizard.
 * 
 * @author WayfarerX
 */
@SuppressWarnings("restriction")//$NON-NLS-1$
public final class ProductExportWizard extends
    org.eclipse.pde.internal.ui.wizards.exports.ProductExportWizard {
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.pde.internal.ui.wizards.exports.ProductExportWizard#
	 *      scheduleExportJob()
	 */
	@Override
	protected void scheduleExportJob() {
		File exportLocation = null;
		try {
			IWizardPage page = getPages()[0];
			Class<ProductExportWizardPage> cls = ProductExportWizardPage.class;
			Method doExportToDirectory = cls.getDeclaredMethod("doExportToDirectory"); //$NON-NLS-1$
			doExportToDirectory.setAccessible(true);
			Method getDestination = cls.getDeclaredMethod("getDestination"); //$NON-NLS-1$
			getDestination.setAccessible(true);
			if ((Boolean) doExportToDirectory.invoke(page)) {
				Method getRootDirectory = cls.getDeclaredMethod("getRootDirectory"); //$NON-NLS-1$
				getRootDirectory.setAccessible(true);
				exportLocation =
				    new File(new File((String) getDestination.invoke(page)),
				        (String) getRootDirectory.invoke(page));
			} else {
				Method getFileName = cls.getDeclaredMethod("getFileName"); //$NON-NLS-1$
				getFileName.setAccessible(true);
				exportLocation =
				    new File(new File((String) getDestination.invoke(page)), new File(
				        (String) getFileName.invoke(page)).getName());
			}
		} catch (Exception e) {
			Throwable t = e;
			if (e instanceof InvocationTargetException)
				t = ((InvocationTargetException) e).getTargetException();
			t.printStackTrace();
			MessageDialog.openError(getShell(), Messages.wizard_failureTitle, t
			    .getMessage());
			return;
		}
		new ProductExportJob(exportLocation);
		super.scheduleExportJob();
	}
}
